package com.updateNew;

import javax.swing.*;

import org.come.until.CutButtonImage;

import java.awt.*;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

//测试类
public class MyJFrame extends JPanel{
	//创建窗体
	private static JFrame myJFrame = new JFrame("游戏更新");

	private static JLabel labtext1,labtext2,labtext3;

	static Long i = 1L;
	static String version = "";

	//构造方法初始化背景图片
	private Image image;
	private ImageIcon image1 = CutButtonImage.getImage("inkImg/old/background/S29.png",20,10);
	private ImageIcon image2 = CutButtonImage.getImage("inkImg/old/background/S27.png",20,10);
//    private ImageIcon image3 = CutButtonImage.getImage("resource/NewUi/shanzi.gif",410,397);


	public MyJFrame(){
		//获取图片
		Image im = new ImageIcon("img/w1131,h603px.png").getImage();
		//设置窗体大小
		myJFrame.setSize(889,500);
		//获取设置背景后的面板
		MyJFrame myJPanel = new MyJFrame(im);
		//添加按钮测试
		myJFrame.setUndecorated(true);
		myJFrame.add(myJPanel);
		myJFrame.setLocationRelativeTo(null);
		myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		myJFrame.setVisible(true);


		Font font = new Font("楷体", 0, 12);
		labtext1 = new JLabel();
		labtext1.setForeground(Color.RED);
		labtext1.setFont(font);
		labtext1.setBounds(150, 440, 280, 30);
		labtext1.setText("准备下载资源...");
		myJPanel.add(labtext1);


		font = new Font("楷体", 0, 16);
		labtext2 = new JLabel();
		labtext2.setForeground(Color.RED);
		labtext2.setFont(font);
		labtext2.setBounds(65, 460, 280, 20);
		labtext2.setText("资源下载中");
		myJPanel.add(labtext2);

		version = getVersion();
		font = new Font("楷体", 0, 12);
		labtext3 = new JLabel();
		labtext3.setForeground(Color.BLACK);
		labtext3.setFont(font);
		labtext3.setBounds(655, 457, 280, 20);
		labtext3.setText("当前版本:"+version);
		myJPanel.add(labtext3);
	}


	public MyJFrame(Image image){
		this.image = image;
	}



	/**
	 * 说明：根据指定URL将文件下载到指定目标位置
	 *
	 * @param urlPath
	 *            下载路径
	 * @param downloadDir
	 *            文件存放目录
	 * @return 返回下载文件
	 */
	@SuppressWarnings("finally")
	public static File downloadFile2(String urlPath, String downloadDir) {
		new MyJFrame();
		File file = null;
		try {
			// 统一资源
			URL url = new URL(urlPath);
			// 连接类的父类，抽象类
			URLConnection urlConnection = url.openConnection();
			// http的连接类
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			//设置超时
			httpURLConnection.setConnectTimeout(1000*5);
			//设置请求方式，默认是GET
			httpURLConnection.setRequestMethod("GET");
			// 设置字符编码
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			// 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
			httpURLConnection.connect();
			// 文件大小
			int fileLength = httpURLConnection.getContentLength();

			// 控制台打印文件大小
//          //system.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");
			labtext1.setBounds(150, 440, 280, 30);
			labtext1.setText("您要下载的文件大小为："+(fileLength / (1024 * 1024)) + "MB");
			labtext2.setBounds(65, 460, 280, 20);
			labtext2.setText("资源下载中");
			labtext3.setBounds(655, 457, 280, 20);
			labtext3.setText("当前版本："+version);
			// 建立链接从请求中获取数据
			URLConnection con = url.openConnection();

			// 使用 try-with-resources 确保资源正确关闭
			try (BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
				 OutputStream out = new FileOutputStream(file)) {
				// 指定文件名称(有需求可以自定义)
				String fileFullName = "game.exe";
				// 指定存放位置(有需求可以自定义)
				String path = downloadDir + File.separatorChar + fileFullName;
				file = new File(path);
				// 校验文件夹目录是否存在，不存在就创建一个目录
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}

				int size = 0;
				Long len = 0L;
				byte[] buf = new byte[2048];
				while ((size = bin.read(buf)) != -1) {
					len += size;
					out.write(buf, 0, size);
//                  //system.out.println("下载了："+len);
//                  //system.out.println("总大小："+fileLength);
					// 控制台打印文件下载的百分比情况
//                  //system.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
					labtext1.setBounds(150, 440, 280, 30);
					Long sx = len * 100;
					i = (long) ( sx / fileLength) ;
					if(i>95) {
						labtext1.setText("正在解压资源......");
						labtext2.setBounds(65, 460, 280, 20);
						labtext2.setText("资源处理中");
						labtext3.setBounds(655, 457, 280, 20);
						labtext3.setText("当前版本："+version);
					}else {
						labtext1.setText("下载进度："+(len * 100 / fileLength) + "%\n");
						labtext2.setBounds(65, 460, 280, 20);
						labtext2.setText("资源下载中");
						labtext3.setBounds(655, 457, 280, 20);
						labtext3.setText("当前版本："+version);
					}
				}
			}
//          //system.out.println("游戏更新成功！正在启动请稍后！！！");
			labtext1.setText("游戏更新成功！正在启动请稍后！！！");
			labtext2.setBounds(65, 460, 280, 20);
			labtext2.setText("正在启动");
			labtext3.setBounds(655, 457, 280, 20);
			labtext3.setText("当前版本："+version);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//          //system.out.println("文件下载失败！");
			labtext1.setText("文件下载失败！");
		} finally {
			return file;
		}

	}



	//重写paintComponent方法
	@Override
	public void paintComponent(Graphics g) {
		//调用父类paintComponent方法绘制其他组件
		super.paintComponent(g);
		//绘制背景图片，大小为窗体大小
		g.drawImage(image, 0, 0,getWidth(),getHeight(), null);
		g.drawImage(image1.getImage(), 150, 465, 500, 10, this);
		g.drawImage(image2.getImage(), 150, 465, Integer.parseInt((i*5)+""), 10, this);
//        g.drawImage(image3.getImage(), 300, 250, 274, 209, this);
	}


	public String getVersion() {
		String inOld = "";
		String ur = System.getProperty("user.dir");
		String filePathOld = ur+"/resource/TXT/ifupdateOld.txt";

		// 使用 try-with-resources 确保资源正确关闭
		try (FileInputStream finOld = new FileInputStream(filePathOld);
			 InputStreamReader readerOld = new InputStreamReader(finOld);
			 BufferedReader buffReaderOld = new BufferedReader(readerOld)) {

			String strTmpOld = "";
			while((strTmpOld = buffReaderOld.readLine())!=null){
//              //system.out.println(strTmpOld);
				inOld = strTmpOld;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inOld;
	}
}
